import { ActivatedRoute, Router } from '@angular/router';
import { Component, OnInit, Input, OnDestroy } from '@angular/core';

import { AlertController } from '@ionic/angular';

import { element } from 'protractor';

import { HttpService } from 'src/app/shared/service/http.service';

import { AppGlobalService } from './../../shared/service/app-global.service';
import { EventService } from '../../shared/service/event.service';
@Component({
  selector: 'app-common-btn',
  templateUrl: './common-btn.component.html',
  styleUrls: ['./common-btn.component.scss'],
})
export class CommonBtnComponent implements OnInit, OnDestroy {

  @Input() tagData: any;
  formData: any;
  keys: any;
  constructor(
    private appGlobalService: AppGlobalService,
    private eventService: EventService,
    private http: HttpService,
    private alert: AlertController,
    private router: Router
  ) {
    this.eventService.eventEmit.on("submitTag", (submitTagData) => {
      console.log("sdlfkjklsfj", submitTagData);
      if (submitTagData) {
        this.formData = submitTagData;
      }
    });
  }

  ngOnInit() {
    // this.demoData();
    console.log(this.tagData);
  }
  managerFromData(data) {
    if (this.formData) {
      // tslint:disable-next-line:prefer-for-of
      for (let i = 0; i < this.formData.data.data.length; i++) {
        if (this.formData.data.data[i].formType === "listCheckbox") {
          this.appGlobalService.showToast("发送邀约成功", 2000, 'middle');
        }
        if (this.formData.data.data[i].formType === "phone") {
          this.appGlobalService.showToast("申请已提交，请等待审核", 2000, 'middle');
        }
        if (this.formData.data.data[i].formType === "textarea" && this.formData.data.data.length === 1) {
          this.appGlobalService.showToast("感谢您的评价", 2000, 'middle');
        }
      }
    } else {
      // if (data.submit.content[data.paramName].listCheckbox) {
      //   this.appGlobalService.showToast("发送邀约成功", 2000, 'middle');
      // }
    }
  }
  /**提交 */
  submiData(data) {
    if (data.action === 'submit') {

      const keyString: string = data.paramName;
      this.keys = keyString.split(',');
      this.keys.forEach(element => {
        if (localStorage.getItem(element)) {
          const obj = JSON.parse(localStorage.getItem(element));
          // 加了参数在下层
          if (obj.data && obj.data.length) {
            obj.data.forEach(e => {
               obj[e.formKey] = e.value;
            });
            delete obj.data;
            data.submit.content[element] = obj;
          } else {
            data.submit.content[element] = obj;
          }

        }
      });

      data.submit.sessionId = localStorage.getItem('sessionId');

      console.log('check --> submit', data.submit);
      this.http.post('application/submit', data.submit, res => {
        // 请求成功
        if (res.success) {
          this.managerFromData(data);
          if (res.type === 'page') {
            const payParams = {
              pageId: res.target,
              params: res.params,
              sessionId: localStorage.getItem('sessionId')
            };
            // to pay
            this.appGlobalService.goToForward(payParams);
            // this.router.navigate(['/return_url'], { queryParams: { p: JSON.stringify(payParams) } });
          }

        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, 'middle');
        }
      });
    }

    //  link
    if (data.action === 'link') {
      if (data.link.type === 'page') {
        const pageParams = {
          pageId: data.link.target,
          params: data.link.params,
          sessionId: localStorage.getItem('sessionId')
        };
        this.appGlobalService.goToForward(pageParams);
      }
    }

    //  const keys = keyString.split(',');
    //  keys.forEach(element => {
    //     if (localStorage.getItem(element)) {
    //       contentObj.element = localStorage.getItem(element);
    //     }

    //    });

  }

  check(data) {
    if (!this.formData) {
      this.submiData(data);
    } else if (this.formData.data) {
      this.verificationFormData(data);
    }
  }

  verificationFormData(data) {
    const keyString = JSON.parse(localStorage.getItem(data.paramName.indexOf(',') > 0 ? data.paramName.split(',')[0] : data.paramName));
    // tslint:disable-next-line:prefer-for-of
    for (let i = 0; i < this.formData.data.data.length; i++) {
      if (this.formData.data.data[i].formType === "listCheckbox") {
        if (!keyString.listCheckbox) {
          this.appGlobalService.showToast('请选择邀约信息', 3000, 'top');
          return;
        }
      }
      if (this.formData.data.data[i].formType === "textarea" && this.formData.data.data[i].required) {
        if (!this.formData.data.data[i].value) {
          this.appGlobalService.showToast('请填写申请原因', 3000, 'top');
          return;
        }
      }
      if (this.formData.data.data[i].formType === "phone" && this.formData.data.data[i].required) {
        if (!keyString.phone) {
          this.appGlobalService.showToast('请输入手机号', 3000, 'top');
          return;
        }
      }
      if (this.formData.data.data[i].formType === "input" && this.formData.data.data[i].required) {
        if (!keyString.input) {
          this.appGlobalService.showToast('请输入验证码', 3000, 'top');
          return;
        }
        if (keyString.input !== this.formData.data.data[i].value) {
          this.appGlobalService.showToast('请输入正确的验证码', 3000, 'top');
          return;
        }
      }
      if (this.formData.data.data[i].formType === "radio") {
        if (!keyString) {
          this.appGlobalService.showToast('请选择结束原因', 3000, 'top');
          return;
        }
        if (keyString.reason === "null") {
          this.appGlobalService.showToast('请填写结束原因', 3000, 'top');
          return;
        } else {
          this.cancel(data);
          return;
        }
      }

    }
    this.submiData(data);
  }

  async cancel(data) {
    const alert = await this.alert.create({
      message: data.question ? data.question : '确定结束服务？',
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
          }
        }, {
          text: '确定',
          cssClass: 'LJ',
          handler: () => {
            this.submiData(data);
          }
        }
      ]
    });

    await alert.present();
  }

  ngOnDestroy(): void {
    // 移除参数
    //  this.keys.forEach(element => {
    //   if (localStorage.getItem(element)) {
    //     localStorage.removeItem(element);
    //   }
    // });
  }
  demoData() {
    this.tagData = {
      type: "tag",
      style: "tag.AppNormalButtonTagLogic",
      name: null,
      layout: "body",
      data: {
        submit: {
          id: "serviceBuy",
          content: {
            quote_name: "",
            quote_id: ""
          }
        },
        cssStyle: "orange",
        action: "submit",
        paramName: "quote_id,quote_name"
      }
    };
  }


}
